import { defineStore } from 'pinia';
import { login as userLogin, logout as userLogout, getUserProfile, LoginData, getInfo } from '@/api/user/index';
import { UserState } from './types';
// import { login, logout, getInfo, logoutforce } from '@/api/login';
import { getToken, setToken, removeToken } from '@/utils/auth';
import Cookies from 'js-cookie';

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    token: getToken(),
    ffKey: '',
    name: '',
    userId: '',
    avatar: '',
    roles: [],
    permissions: [],
    ismanager: Cookies.get('ismanager') || '',
    msgShield: false, // 页面切换了 屏蔽请求提示
  }),
  getters: {
    userProfile(state: UserState): UserState {
      return { ...state };
    },
  },
  actions: {
    setToken(token) {
      this.token = token;
    },
    setFfkey(ffKey) {
      this.ffKey = ffKey;
    },
    setName(name) {
      this.name = name;
    },
    setUserId(userId) {
      this.userId = userId;
    },
    setAvatar(avatar) {
      this.avatar = avatar;
    },
    setRoles(roles) {
      this.roles = roles;
    },
    setPermissions(permissions) {
      this.permissions = permissions;
    },
    switchPage() {
      this.msgShield = !this.msgShield;
    },
    setIsManager(ismanager) {
      this.ismanager = ismanager;
    },
    // 登录
    Login(userInfo) {
      userInfo.username = userInfo.username.trim();
      return new Promise<void>((resolve, reject) => {
        userLogin(userInfo)
          .then((res) => {
            const d = res.data;
            setToken(d.ffToken);
            this.setToken(d.ffToken);
            this.setFfkey(d.ffKey);
            this.setIsManager(d.ismanager);
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 获取用户信息
    GetInfo() {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            const user = res.user;
            console.log('用户信息', user.userId);
            // // 个人中心使用
            // sessionStorage.setItem(
            //   "userInfo",
            //   JSON.stringify({ userName: user.userName, userId: user.userId })
            // );
            const avatar = user.avatar == '' ? require('@/assets/images/profile.jpg') : process.env.VUE_APP_BASE_API + user.avatar;
            if (res.roles && res.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              this.setRoles(res.roles);
              this.setPermissions(res.permissions);
            } else {
              this.setRoles(['ROLE_DEFAULT']);
            }
            this.setName(user.userName);
            this.setUserId(user.userId);
            this.setAvatar(avatar);
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    clearToken() {
      this.setToken('');
      this.setRoles([]);
      this.setPermissions([]);
      removeToken();
    },

    // switchRoles() {
    //   return new Promise((resolve) => {
    //     this.role = this.role === 'user' ? 'user' : 'admin';
    //     resolve(this.role);
    //   });
    // },
    // 设置用户的信息
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },
    // 重置用户信息
    resetInfo() {
      this.$reset();
    },
    // 获取用户信息
    async info() {
      const result = await getUserProfile();
      this.setInfo(result);
    },
    // 异步登录并存储token
    async login(loginForm: LoginData) {
      const result = await userLogin(loginForm);
      const token = result?.token;
      if (token) {
        setToken(token);
      }
      return result;
    },
    // Logout
    async Logout() {
      return new Promise<void>((resolve, reject) => {
        userLogout()
          .then(() => {
            this.clearToken();
            location.href = process.env.VUE_APP_PATH!;
            resolve();
          })
          .catch((error) => {
            this.clearToken();
            location.href = process.env.VUE_APP_PATH!;
            reject(error);
          });
      });
    },
  },
});
